package com.gx.smart.building.ui.home.fragment;

import android.app.Activity;
import android.content.Intent;
import android.view.ViewGroup;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.databinding.DataBindingUtil;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.EncodeUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.gx.smart.base.BaseAdapter;
import com.gx.smart.base.BaseMVVMFragmentV2;
import com.gx.smart.building.R;
import com.gx.smart.building.databinding.HomeFragmentBinding;
import com.gx.smart.building.ui.assets.AssetsActivity;
import com.gx.smart.building.ui.assets.AssetsDetailActivity;
import com.gx.smart.building.ui.home.adapter.FunctionAdapter;
import com.gx.smart.building.ui.home.model.Function;
import com.gx.smart.building.ui.home.model.Params;
import com.gx.smart.building.ui.home.model.QRContent;
import com.gx.smart.building.ui.home.viewmodel.HomeViewModel;
import com.gx.smart.building.ui.inspection.InspectionActivity;
import com.gx.smart.building.ui.knowledge.KnowledgeActivity;
import com.gx.smart.building.ui.maintain.MaintainActivity;
import com.gx.smart.building.ui.message.MessageActivity;
import com.gx.smart.building.ui.repair.RepairActivity;
import com.gx.smart.building.ui.report.FaultReportActivity;
import com.gx.smart.building.ui.spare.SelectAreaActivity;
import com.gx.smart.building.ui.swap.MySwapWorkActivity;
import com.gx.smart.building.ui.swap.SwapWorkActivity;
import com.gx.smart.building.ui.warning.WarningListActivity;
import com.mylhyl.circledialog.CircleDialog;
import com.orhanobut.logger.Logger;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.bean.ZxingConfig;
import com.yzq.zxinglibrary.common.Constant;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends BaseMVVMFragmentV2<HomeViewModel> implements BaseAdapter.OnItemClickListener<Function> {

    private FunctionAdapter adapter;
    private HomeFragmentBinding binding;


    @Override
    public boolean getLeft() {
        return false;
    }

    @Override
    public int onBindLayout() {
        return R.layout.home_fragment;
    }

    @Override
    public String getToolbarTitle() {
        return "医院后勤管理";
    }

    @Override
    protected Class<HomeViewModel> onBindViewModel() {
        return HomeViewModel.class;
    }


    @Override
    public void initContentView(ViewGroup root) {
        adapter = new FunctionAdapter(requireContext());
        binding = DataBindingUtil.inflate(getLayoutInflater(), onBindLayout(), root, true);
        binding.setHomeFragment(this);
        binding.setLifecycleOwner(getViewLifecycleOwner());
        adapter.setItemClickListener(this);
        binding.recyclerView.setAdapter(adapter);
    }

    private ActivityResultLauncher<Intent> scanQRCode = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(), result -> {
                if (result.getResultCode() == Activity.RESULT_OK) {
                    Intent data = result.getData();
                    if (data != null) {
                        String content = data.getStringExtra(Constant.CODED_CONTENT);
                        Logger.e("qr code : " + content);
                        String jsonStr = new String(EncodeUtils.base64Decode(content));
                        QRContent qrContent = GsonUtils.fromJson(jsonStr, QRContent.class);
                        jumpPageByType(qrContent.getType(), qrContent.getParams());
                    }
                }
            }
    );

    private void jumpPageByType(int type, Params params) {
        switch (type) {
            case 1:
                jumpAssetDetailPage(params);
                break;
            case 2:
                jumpMySwapPage(params);
                break;
        }
    }

    private void jumpMySwapPage(Params params) {
        Intent intent = new Intent(requireActivity(), MySwapWorkActivity.class);
        intent.putExtra("id", params.getId());
        startActivity(intent);
    }

    private void jumpAssetDetailPage(Params params) {
        Intent intent = new Intent(requireActivity(), AssetsDetailActivity.class);
        intent.putExtra("id", params.getId());
        startActivity(intent);
    }

    @Override
    public void onStart() {
        super.onStart();
        viewModel.indexTotal();
    }

    @Override
    protected void initData() {

        List<Function> functionList = new ArrayList<>();
        Function item1 = new Function();
        item1.setResId(R.mipmap.ic_repair);
        item1.setContent("维修工单");
        functionList.add(item1);

        Function item2 = new Function();
        item2.setResId(R.mipmap.ic_inspection);
        item2.setContent("巡检任务");
        functionList.add(item2);

        Function item3 = new Function();
        item3.setResId(R.mipmap.ic_maintain);
        item3.setContent("保养任务");
        functionList.add(item3);

        Function item4 = new Function();
        item4.setResId(R.mipmap.ic_warning);
        item4.setContent("全部告警");
        functionList.add(item4);


        Function item5 = new Function();
        item5.setResId(R.mipmap.ic_assets_bill);
        item5.setContent("设备台账");
        functionList.add(item5);

        Function item6 = new Function();
        item6.setResId(R.mipmap.ic_knowledge);
        item6.setContent("知识库");
        functionList.add(item6);

        Function item7 = new Function();
        item7.setResId(R.mipmap.ic_message);
        item7.setContent("我的消息");
        functionList.add(item7);

        Function item8 = new Function();
        item8.setResId(R.mipmap.ic_spare_part);
        item8.setContent("备件申请");
        functionList.add(item8);

        Function item9 = new Function();
        item9.setResId(R.mipmap.ic_fault_report);
        item9.setContent("故障上报");
        functionList.add(item9);

        Function item10 = new Function();
        item10.setResId(R.mipmap.ic_scan);
        item10.setContent("扫一扫");
        functionList.add(item10);

        Function item11 = new Function();
        item11.setResId(R.mipmap.ic_swap_work);
        item11.setContent("交接班");
        functionList.add(item11);

        adapter.addAll(functionList);
        viewModel.getWorkOrderQuantity()
                .observe(getViewLifecycleOwner(),
                        workOrderQuantity -> {
                            functionList.get(0).setNum(workOrderQuantity);
                            adapter.notifyItemChanged(0);
                        });
        viewModel.getPlanTaskQuantity1()
                .observe(getViewLifecycleOwner(),
                        planTaskQuantity1 -> {
                            functionList.get(1).setNum(planTaskQuantity1);
                            adapter.notifyItemChanged(1);
                        });
        viewModel.getPlanTaskQuantity2()
                .observe(getViewLifecycleOwner(),
                        planTaskQuantity2 -> {
                            functionList.get(2).setNum(planTaskQuantity2);
                            adapter.notifyItemChanged(2);
                        });
        viewModel.getMsgAlarmQuantity()
                .observe(getViewLifecycleOwner(),
                        msgAlarmQuantity -> {
                            functionList.get(3).setNum(msgAlarmQuantity);
                            adapter.notifyItemChanged(3);
                        });
        viewModel.getMessageQuantity()
                .observe(getViewLifecycleOwner(),
                        messageQuantity -> {
                            functionList.get(6).setNum(messageQuantity);
                            adapter.notifyItemChanged(6);
                        });
    }

    @Override
    public void onItemClick(Function function, int position) {

        switch (position) {
            case 0:
                ActivityUtils.startActivity(new Intent(getActivity(), RepairActivity.class));
                break;
            case 1:
                ActivityUtils.startActivity(new Intent(getActivity(), InspectionActivity.class));
                break;
            case 2:
                ActivityUtils.startActivity(new Intent(getActivity(), MaintainActivity.class));
                break;
            case 3:
                ActivityUtils.startActivity(new Intent(getActivity(), WarningListActivity.class));
                break;
            case 4:
                ActivityUtils.startActivity(new Intent(getActivity(), AssetsActivity.class));
                break;
            case 5:
                ActivityUtils.startActivity(new Intent(getActivity(), KnowledgeActivity.class));
                break;
            case 6:
                ActivityUtils.startActivity(new Intent(getActivity(), MessageActivity.class));
                break;
            case 7:
                ActivityUtils.startActivity(new Intent(getActivity(), SelectAreaActivity.class));
                break;
            case 8:
                ActivityUtils.startActivity(new Intent(getActivity(), FaultReportActivity.class));
                break;
            case 9:
                scan();
                break;
            case 10:
                ActivityUtils.startActivity(new Intent(getActivity(), SwapWorkActivity.class));
                break;
        }
    }

    private void scan() {
        if (AndPermission.hasPermissions(requireActivity(), Permission.CAMERA, Permission.READ_EXTERNAL_STORAGE)) {
            // Storage permission are allowed.
            Intent intent = new Intent(requireActivity(), CaptureActivity.class);
            ZxingConfig config = new ZxingConfig();
            config.setFullScreenScan(true);//是否全屏扫描  默认为true  设为false则只会在扫描框中扫描
            intent.putExtra(Constant.INTENT_ZXING_CONFIG, config);
            scanQRCode.launch(intent);
            return;
        }
        AndPermission.with(this)
                .runtime()
                .permission(Permission.CAMERA, Permission.READ_EXTERNAL_STORAGE)
                .onGranted(data -> scan())
                .onDenied(data -> new CircleDialog.Builder()
                        .setTitle("获取权限")
                        .setText("请允许获取对应的权限，否则不能运行？")
                        .setPositive("确定", null)
                        .show(requireActivity().getSupportFragmentManager())).start();
    }
}